package com.daisuxia.back.controller;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.service.IBackRoleService;
import com.daisuxia.back.service.IBackUserService;
import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.TreeUtil;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BackLog;
import com.daisuxia.web.pojo.BackTree;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

@Controller
@RequestMapping("user/")
public class UserController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private IBackUserService backUserService;
	@Autowired
	private IBackRoleService backRoleService;

	@RequestMapping("getUserPage")
	public String getUserPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			 
			PageConfig<BackUser> pageConfig = backUserService.findPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "user/userList";
	}

	/**
	 * xiangxiaoyan 跳转到添加页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("saveUpdateUser")
	public String saveUpdateUser(HttpServletRequest request, HttpServletResponse response, Model model, BackUser backUser) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (params.containsKey("id")) {
					// 更新的页面跳转
					backUser = backUserService.findOneUser(params);
					model.addAttribute("backUser", backUser);
				}
				url = "user/saveUpdateUser";
			} else {
				// 更新或者添加操作
				if (backUser.getId() != null) {
					backUserService.updateById(backUser);
				} else {
					backUser.setAddIp(this.getIpAddr(request));

					AESUtil aesEncrypt = new AESUtil();
					backUser.setUserPassword(MD5coding.MD5(aesEncrypt.encrypt(backUser.getUserPassword(), "")));
					backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "saveUpdateUser", backUser.toString()));
					backUserService.insert(backUser);
				}
				SpringUtils.renderDwzResult(response, true, "操作成功", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
		} catch (Exception e) {
			if (url == null) {
				erroMsg = "服务器异常，请稍后重试！";
				if (e.getLocalizedMessage().indexOf("UK_user_account") >= 0) {
					erroMsg = "用户名重复！";
				}
				if (e.getLocalizedMessage().indexOf("uk_user_mobile") >= 0) {
					erroMsg = "手机号码重复！";
				}
				SpringUtils
						.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
			logger.error("添加权限信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}

	/**
	 * 删除角色
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("deleteUser")
	public void deleteUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		boolean flag = false;
		try {
			Integer id = Integer.parseInt(params.get("id").toString());
			backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "deleteUser", id+""));
			backUserService.deleteById(id);
			flag = true;
		} catch (Exception e) {
			logger.error("deleteRole error", e);
		}
		SpringUtils.renderDwzResult(response, flag, flag ? "删除用户成功" : "删除用户失败", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId")
				.toString());
	}

	/**
	 * 用戶授权
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */

	@RequestMapping("saveUserRole")
	public String saveUserRole(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {
			BackUser backUser = this.loginAdminUser(request);
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				params.put("userId", backUser.getId());
				List<BackTree> userAll = backRoleService.findRoleTree(params);
				Integer id = Integer.valueOf(params.get("id").toString());
				params.put("userId", id);
				List<BackTree> haveList = backRoleService.findRoleTree(params);
				String outGroupHtml = TreeUtil.getTreeStringWidthCheckBoxOne(userAll, haveList, "roleIds");
				model.addAttribute("outGroupHtml", outGroupHtml);
				params.put("url", "user/saveUserRole");
				params.put("ajaxType", "dialogAjaxDone");
				url = "showRolesRight";
			} else {
				url = null;
				params.put("roleIds", request.getParameterValues("roleIds"));
				backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "saveUserRole",params+""));
				backUserService.addUserRole(params);
				SpringUtils.renderDwzResult(response, true, "用户授权成功", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
		} catch (Exception e) {
			if (url == null) {
				SpringUtils.renderDwzResult(response, false, "操作失败", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			} else {
				erroMsg = "服务器异常，请稍后重试！";
			}
			logger.error("用户授权失败，异常信息:", e);
		}
		model.addAttribute("params", params);
		model.addAttribute(MESSAGE, erroMsg);
		return url;
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("updateUserPassword")
	public String updateUserPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		String target = "";
		boolean bool = false;
		String errorMsg = "";
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				target = "user/updateUserPwd";
			} else {
				AESUtil aesEncrypt = new AESUtil();
				String oldPassword = MD5coding.MD5(aesEncrypt.encrypt(params.get("oldPassword").toString(), ""));
				BackUser backUser = this.loginAdminUser(request);
				if (!backUser.getUserPassword().equals(oldPassword)) {
					errorMsg = "原密码错误！";
				} else {
					String newPassword = MD5coding.MD5(aesEncrypt.encrypt(params.get("newPassword").toString(), ""));
					BackUser backUser2 = new BackUser();
					backUser2.setId(backUser.getId());
					backUser2.setUserPassword(newPassword);
					backUserService.insertLog(new BackLog(loginAdminUser(request).getId(), "updateUserPassword",backUser2.toString()));
					backUserService.updatePwdById(backUser2);
					bool = true;
				}
				SpringUtils.renderDwzResult(response, bool, bool ? "操作成功" : "操作失败，" + errorMsg, DwzResult.CALLBACK_CLOSECURRENT);
				target = null;
			}
		} catch (Exception e) {
			logger.error("updateUserPassWord error ", e);
		}
		return target;
	}
}
